package com.supermap.localization.impl;

import java.io.BufferedReader;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Map;

import org.apache.oro.text.regex.MalformedPatternException;

import com.supermap.localization.api.FileReplacer;
import com.supermap.localization.api.LineReplacer;
import com.supermap.localization.commontypes.SampleInfo;

public class FileReplacerImpl implements FileReplacer {

    private LineReplacer lineReplacer;

    public void setLineReplacer(LineReplacer lineReplacer) {
        this.lineReplacer = lineReplacer;
    }

    @Override
    public String replace(Path sourcePath, Map<String, SampleInfo> sampleInfos) throws IOException, MalformedPatternException {
        StringBuilder sb = new StringBuilder();
        BufferedReader br = null;
        try {
            br = Files.newBufferedReader(sourcePath, StandardCharsets.UTF_8);
            String line = null;
            String lineSeparator = System.getProperty("line.separator");
            while ((line = br.readLine()) != null) {
                line = lineReplacer.replace(line, sampleInfos);
                sb.append(line);
                sb.append(lineSeparator);
            }
        } finally {
            br.close();
        }
        return sb.toString();
    }

}
